package com.jtcoding.chat.common;

import java.io.*;

/**
 * @author jason.tang
 * @create 2019-02-19 14:47
 * @description
 */
public class FileUtils implements Serializable {

    public static byte[] fileToBytes(File file) throws Exception {
        if (file != null && file.exists() && file.isFile()) {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] tmpBytes = new byte[2048];
            int ch;
            while ((ch = is.read(tmpBytes)) != -1) {
                baos.write(tmpBytes, 0, ch);
            }
            return baos.toByteArray();
        }
        throw new Exception("无效文件!");
    }

    public static boolean bytesToFile(byte[] bytes, File file) throws IOException {
        boolean write;
        try {
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            write = true;
        } catch (Exception e) {
            write = false;
            e.printStackTrace();
        }
        return write;
    }

    public static boolean bytesToFile(byte[] bytes, String filePath) {
        boolean write;
        try {
            FileOutputStream fos = new FileOutputStream(new File(filePath));
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            write = true;
        } catch (Exception e) {
            write = false;
            e.printStackTrace();
        }
        return write;
    }

    public static boolean copy(File fromFile, File toFile) throws Exception {
        byte[] bytes = fileToBytes(fromFile);
        return bytesToFile(bytes, toFile);
    }
}